//
//  ZGL24hVC.m
//  Faker
//
//  Created by dllo on 15/11/2.
//  Copyright © 2015年 dllo. All rights reserved.
//

#import "ZGLmyVC.h"

#import "ZGLLoginVC.h"

#import "ZGLAboutUsVC.h"
#import "ZGLAdviceVC.h"


@interface ZGLmyVC ()<UITableViewDataSource, UITableViewDelegate>
@property(nonatomic, retain)UITableView *table;
@property(nonatomic, retain)NSArray *dicArr;
@property(nonatomic, retain)UISwitch *swi1;//夜间模式开关
/* 显示缓存大小 */
@property (nonatomic, assign) float cachSize;
@end

@implementation ZGLmyVC

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"zaihufanhui"] style:(UIBarButtonItemStyleDone) target:self action:@selector(leftBarButtonItem:)];
    self.navigationItem.leftBarButtonItem.tintColor = [UIColor whiteColor];
    
    [self.navigationController.navigationBar setTitleTextAttributes:@{NSForegroundColorAttributeName : [UIColor whiteColor]}];
    self.title = @"个人中心";

    _dicArr = [NSArray arrayWithObjects:@"主题切换",
                                        @"夜间模式",
                                        @"清除缓存",
                                        @"要闻推送",
                                        @"我的收藏",
                                        @"用户反馈",
                                        @"关于我们", nil];
    [self createTableView];
}

- (void)leftBarButtonItem:(UIBarButtonItem *)button {
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)viewWillAppear:(BOOL)animated{
     self.automaticallyAdjustsScrollViewInsets = NO;
    [super viewWillAppear:animated];
    self.tabBarController.tabBar.hidden = YES;
    self.view.backgroundColor = backColor;
    
    //这里是标题view
    _table.tableHeaderView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, Width, (int)250*ScaleX)];
    _table.tableHeaderView.backgroundColor = naviColor;
    if (logName == nil) {
        UILabel *lab = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, 200, 20)];
        lab.center = _table.tableHeaderView.center;
        lab.textAlignment = NSTextAlignmentCenter;
        lab.text = @"请登录";
        [_table.tableHeaderView addSubview:lab];
        UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(login:)];
        [_table.tableHeaderView addGestureRecognizer:tapGesture];
    }else{
        UILabel *lab = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, 200, 20)];
        lab.center = _table.tableHeaderView.center;
        lab.textAlignment = NSTextAlignmentCenter;
        lab.text = [NSString stringWithFormat:@"Welcome, %@", logName];
        [_table.tableHeaderView addSubview:lab];
    }
    
    _table.backgroundColor = backColor;
    [_table reloadData];
}

- (void)viewWillDisappear:(BOOL)animated{
     self.automaticallyAdjustsScrollViewInsets = YES;
    [super viewWillDisappear:animated];
    self.tabBarController.tabBar.hidden = NO;
}

- (void)createTableView{
    _table = [[UITableView alloc]initWithFrame:CGRectMake(0, 64, Width, Height-64) style:UITableViewStylePlain];
    _table.bounces = NO;
    _table.tableFooterView = [[UIView alloc]init];
    _table.delegate = self;
    _table.dataSource = self;
    [self.view addSubview:_table];
    [_table registerClass:[UITableViewCell class] forCellReuseIdentifier:@"UITableViewCell"];
}

- (void)login:(UITapGestureRecognizer *)tap{
    ZGLLoginVC *login = [[ZGLLoginVC alloc]init];
    [self.navigationController pushViewController:login animated:YES];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    //不使用重用池
    UITableViewCell *cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"UITableViewCell"];
    cell.textLabel.text = _dicArr[indexPath.section*5+indexPath.row];
    cell.backgroundColor = foreColor;
    cell.textLabel.textColor = artiColor;
    
    NSInteger num = [self getNum:indexPath];//num指cell是数组第几个
    //这里写cell上加什么零件
    switch (num) {
        case 0:{
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            for (int i=0; i<4; i++) {
                UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
                button.frame = CGRectMake(Width-210+50*i, 15, 45, 30);
                button.backgroundColor = colorStyle[i];
                button.tag = 3200+i;
                [button addTarget:self action:@selector(changeColor:) forControlEvents:UIControlEventTouchUpInside];
                [cell.contentView addSubview:button];
            }
        }return cell;
        case 1:{
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            _swi1 = [[UISwitch alloc]init];
            _swi1.frame = CGRectMake(Width-60, 15, 45, 30);
            _swi1.onTintColor = naviColor;
            _swi1.tintColor = [UIColor lightGrayColor];
            [_swi1 setOn:[ZGLsettings shareSettings].isNight];
            if (_swi1.isOn) {
                _swi1.thumbTintColor = [UIColor lightGrayColor];
            }else{
                _swi1.thumbTintColor = naviColor;
            }
            [_swi1 addTarget:self action:@selector(swi1Change:) forControlEvents:UIControlEventValueChanged];
            [cell.contentView addSubview:_swi1];
        }return cell;
        case 2:{
            /* 获取缓存数据文件路径 */
            NSString *cachPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory,NSUserDomainMask, YES) objectAtIndex:0];
            /* 调用方法 获得缓存数据大小 */
            self.cachSize = [self folderSizeAtPath:cachPath];
            UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(200 * ScaleX, 15 * ScaleX, 165 * ScaleX, 30 * ScaleX)];
            label.textAlignment = 2;
            label.textColor = [UIColor colorWithWhite:0.554 alpha:1.000];
            label.font = [UIFont systemFontOfSize:12];
            /* 将缓存数据赋值到label 用于实时显示 */
            label.text = [NSString stringWithFormat:@"当前共有缓存%.2fMB", self.cachSize];
            [cell addSubview:label];
        }return cell;
        case 3:{
            
        }return cell;
        case 4:{
            
        }return cell;
        case 5:{
            
        }return cell;
        case 6:{
            
        }return cell;
        default:
            return cell;
    }
}

- (void)changeColor:(UIButton *)button{
    naviColor = button.backgroundColor;
    self.navigationController.navigationBar.barTintColor = naviColor;
    _table.tableHeaderView.backgroundColor = naviColor;
    NSNumber *cs = [NSNumber numberWithInteger:button.tag-3200];
    [[ZGLsettings shareSettings] changeNaviColor:cs];
    
    self.tabBarController.tabBar.barTintColor = naviColor;
    
    UIView *view = [_table viewWithTag:3003];
    view.backgroundColor = naviColor;
    
    _swi1.onTintColor = naviColor;
    if (_swi1.isOn) {
        _swi1.thumbTintColor = [UIColor lightGrayColor];
    }else{
        _swi1.thumbTintColor = naviColor;
    }
}//导航栏变色

- (void)swi1Change:(UISwitch *)swi{
    [ZGLsettings shareSettings].isNight = swi.isOn;
    [[ZGLsettings shareSettings] changeNight];//存入本地
    if (_swi1.isOn) {
        _swi1.thumbTintColor = [UIColor lightGrayColor];
    }else{
        _swi1.thumbTintColor = naviColor;
    }
    self.view.backgroundColor = backColor;
    _table.backgroundColor = backColor;
    [_table reloadData];
}

- (NSInteger)getNum:(NSIndexPath *)path{
    switch (path.section) {
        case 0:
            return path.row;
        case 1:
            return 5 + path.row;
        default:
            return 0;
    }
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (section == 0) {
        return 5;
    }else{
        return 2;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 60;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if (section == 1) {
        return 20;
    }else{
        return 0;
    }
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UIView *view = [[UIView alloc]init];
    view.backgroundColor = naviColor;
    view.tag = 3003;
    return view;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    self.view.userInteractionEnabled = NO;
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    [self selectWithTag:indexPath.section*5+indexPath.row];
    self.view.userInteractionEnabled = YES;
}

//这里写cell点击事件
- (void)selectWithTag:(NSInteger)tag{
    switch (tag) {
        case 0:{}
            break;
        case 1:{}
            break;
        case 2:{
            UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"提示" message:@"您将要清除缓存" preferredStyle:UIAlertControllerStyleAlert];
            UIAlertAction *action1 = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                NSString *cachPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory,NSUserDomainMask, YES) objectAtIndex:0];
                [self cleanCacheDataWithCachPath:cachPath];
                [self.table reloadData];
            }];
            UIAlertAction *action2 = [UIAlertAction actionWithTitle:@"Cancel" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            }];
            [alertController addAction:action1];
            [alertController addAction:action2];
            [self presentViewController:alertController animated:YES completion:nil];
        }
            break;
        case 3:{}
            break;
        case 4:{}
            break;
        case 5:{
            ZGLAdviceVC *adviceVC = [[ZGLAdviceVC alloc] init];
            [self.navigationController pushViewController:adviceVC animated:YES];
        }
            break;
        case 6:{
            ZGLAboutUsVC *AboutVC = [[ZGLAboutUsVC alloc] init];
            [self.navigationController pushViewController:AboutVC animated:YES];
        
        }
            break;
        default:
            break;
    }
}



- (void)dealloc{
    _table.dataSource = nil;
    _table.delegate = nil;
}

#pragma mark  - 缓存数据部分
#pragma mark  ** 获取单个文件大小
/* 获取单个文件数据大小*/
- (long long)fileSizeAtPath:(NSString*)filePath {
    /* 创建文件管理者对象 */
    NSFileManager *manager = [NSFileManager defaultManager];
    /* 判断文件中是否存在该文件 */
    if ([manager fileExistsAtPath:filePath]) {
        /* 返回文件大小 */
        return [[manager attributesOfItemAtPath:filePath error:nil] fileSize];
    }
    /* 不存在则返回0 */
    return 0;
}
#pragma mark  ** 获取整个缓存文件下的数据大小

- (float)folderSizeAtPath:(NSString*)folderPath {
    /* 创建文件管理者对象 */
    NSFileManager *manager = [NSFileManager defaultManager];
    /* 如果没有, 则返回0 */
    if (![manager fileExistsAtPath:folderPath]) return 0;
    
    NSEnumerator *childFilesEnumerator = [[manager subpathsAtPath:folderPath] objectEnumerator];
    NSString *fileName;
    long long folderSize = 0;
    /* 挨个遍历, 判断是否全部遍历 */
    while ((fileName = [childFilesEnumerator nextObject]) != nil) {
        NSString *fileAbsolutePath = [folderPath stringByAppendingPathComponent:fileName];
        /* 逐个计算数据大小 */
        folderSize += [self fileSizeAtPath:fileAbsolutePath];
    }
    /* 转换为字节返回 */
    return folderSize / (1024.0 * 1024.0);
}
#pragma mark  ** 清除缓存数据

- (void)cleanCacheDataWithCachPath:(NSString *)cachPath {
    
    /* 获取cachPath缓存文件夹中的数组文件 */
    NSArray *files = [[NSFileManager defaultManager] subpathsAtPath:cachPath];
    /* 遍历数组文件, 获取每个路径 */
    for (NSString *per in files) {
        NSError *error;
        /* 拼接路径 */
        NSString *path = [cachPath stringByAppendingPathComponent:per];
        /* 判断是否存在该文件路径, 存在就清除 */
        if ([[NSFileManager defaultManager] fileExistsAtPath:path]) {
            [[NSFileManager defaultManager] removeItemAtPath:path error:&error];
        }
    }
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
